﻿using System.Runtime.Caching;

namespace App.Tools.Caches
{
    internal class appMemoryCache : ICache
    {
        object ICache.this[string key] { get => cache.Get(key); set => Add(key, value); }
        public MemoryCache cache
        {
            get
            {
                return MemoryCache.Default;
            }
        }
        public int Count => (int)cache.GetCount();


        /// <summary>
        /// 永久添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="data"></param>
        public void Add(string key, object data)
        {
            Add(key, data, -1);
        }

        public void Add(string key, object data, int cacheSecondTime)
        {
            if (cache.Contains(key))
            {
                cache.Remove(key);
            }

            var policy = new CacheItemPolicy();

            if (cacheSecondTime > 0)
            {
                policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromSeconds(cacheSecondTime);
            }

            cache.Add(new CacheItem(key, data), policy);
        }
        public bool Contains(string key)
        {
            return cache.Contains(key);
        }
        public T Get<T>(string key)
        {
            if (cache.Contains(key))
            {
                return (T)cache.Get(key);
            }
            else
            {
                return default(T);
            }
        }
        public void Remove(string key)
        {
            cache.Remove(key);
        }

        public void Remove(List<string> keys)
        {
            foreach (var item in keys)
            {
                cache.Remove(item);
            }
        }
        public void RemoveAll()
        {
            foreach (var item in cache)
            {
                this.Remove(item.Key);
            }
        }

    }
}

